/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import React, {useRef, useState, useCallback} from 'react';
import {View, Text, TextInput, Button, Image, StyleSheet, TouchableOpacity, useColorScheme} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {AdaptiveSheet, SHEET_TYPE} from '@hadss/react-native-adaptive-sheet';
import type {AdaptiveSheetMethods} from '@hadss/react-native-adaptive-sheet';
import {BreakpointsReference, GridCol, GridRow, GridRowDirection, Fold} from '@hadss/react_native_adaptive_layout/src';
import type {ReactNode} from 'react';

const Page = (): ReactNode => {
  const bottomDraggableRef = useRef<AdaptiveSheetMethods>(null);
  const [bottomDraggableIndex, setBottomDraggableIndex] = useState(-1);

  const inputRef = useRef<TextInput>(null);
  const colorScheme = useColorScheme(); // 获取系统颜色方案

  /**
   * Dark Mode 颜色映射
   * 根据系统颜色方案返回对应的颜色值
   */
  const colors = {
    // 背景颜色
    modalBackground: colorScheme === 'dark' ? '#1c1c1e' : '#ffffff',
    rowBackground: colorScheme === 'dark' ? '#555556' : '#f9d3d3',
    colBackground: colorScheme === 'dark' ? '#484849' : '#f4b0b0',

    // 文本颜色
    text: colorScheme === 'dark' ? '#ffffff' : '#333333',
  };

  // 底部弹窗状态变化回调
  const handleStateChange = useCallback((index: number): void => {
    setBottomDraggableIndex(index);
    if (index === -1) {
      inputRef.current?.blur(); // 手动触发失焦 隐藏键盘
    }
  }, []);

  const list = Array.from({length: 12}, (_, i) => i);
  return (
    <SafeAreaProvider>
      <GestureHandlerRootView style={{flex: 1}}>
        <SafeAreaView style={styles.container} edges={['top', 'left', 'right']}>
          <GridRow
            style={[styles.gridRow, {backgroundColor: colors.rowBackground}]}
            columns={{
              xs: 4,
              sm: 4,
              md: 8,
              lg: 12,
              xl: 12,
            }}
            gutter={40}
            breakpoints={{
              reference: BreakpointsReference.ComponentSize,
            }}
            direction={GridRowDirection.Row}>
            {list.map((item, index) => (
              <GridCol
                offset={0}
                order={0}
                span={1}
                style={[styles.gridItem, {backgroundColor: colors.colBackground}]}
                key={index}>
                <View style={styles.gridItemContent}></View>
              </GridCol>
            ))}
          </GridRow>
          <View style={styles.buttonGroup}>
            <Button title="模态页面" onPress={(): void => bottomDraggableRef.current?.snapToIndex(0)} />
          </View>
          <AdaptiveSheet
            prefertype={SHEET_TYPE.BOTTOM}
            ref={bottomDraggableRef}
            index={bottomDraggableIndex}
            onStateChange={(index: number): void => handleStateChange(index)}
            // 底部弹窗特定配置
            bottomSheetProps={{
              snapPoints: '70%', // 单个值表示默认高度，可在 40%-90% 范围内自由拖拽
              enableDragToClose: true, // 拖拽到 33% 以下关闭
              enablePanDownToClose: true, // 快速下滑关闭
              enableHandlePanningGesture: true, // 是否可拖拽
              backgroundStyle: {
                backgroundColor: colors.modalBackground,
                borderTopLeftRadius: 32,
                borderTopRightRadius: 32,
                paddingTop: 0,
              },
              animationConfigs: {
                duration: 250,
              },
            }}>
            <View style={styles.sheetHeaderContainer}>
              <View style={styles.sheetHeader}>
                <Text style={[styles.sheetHeaderText, {color: colors.text}]}>标题区</Text>
                <TouchableOpacity
                  style={styles.sheetHeaderClose}
                  onPress={(): void => bottomDraggableRef.current?.close()}>
                  <Image style={{width: 16, height: 16}} source={require('../../../assets/modal/close.png')} />
                </TouchableOpacity>
              </View>
            </View>
            <View style={styles.sheetContentContainer}>
              <View style={styles.sheetContent}>
                <Text style={styles.sheetContentTitle}>内容区</Text>
                <View style={styles.inputWrapper}>
                  <TextInput style={styles.input} ref={inputRef} />
                </View>
              </View>
            </View>
          </AdaptiveSheet>
        </SafeAreaView>
      </GestureHandlerRootView>
    </SafeAreaProvider>
  );
};

export default Page;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    position: 'relative',
  },
  gridRow: {
    height: '100%',
    flex: 1,
    justifyContent: 'space-around',
    backgroundColor: '#f9d3d3',
  },
  gridItem: {
    backgroundColor: '#f4b0b0',
  },
  gridItemContent: {
    height: '100%',
  },
  gridItemOdd: {
    backgroundColor: '#ae959e',
  },
  gridItemEven: {
    backgroundColor: '#fff',
  },
  buttonGroup: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sheetHeaderContainer: {
    paddingHorizontal: 30,
  },
  sheetHeader: {
    paddingTop: 0,
    paddingBottom: 12,
    borderBottomColor: '#DDD',
    borderBottomWidth: 1,
    marginBottom: 16,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  sheetHeaderText: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
  },
  sheetHeaderClose: {
    backgroundColor: 'rgba(241, 243, 245, 1)',
    borderRadius: 30,
    padding: 6,
  },
  sheetContentContainer: {
    flex: 1,
    alignItems: 'center',
  },
  sheetContent: {
    width: '83%',
    flex: 1,
    marginBottom: 40,
    backgroundColor: '#9dc3e3',
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  sheetContentTitle: {
    fontSize: 14,
  },
  inputWrapper: {
    height: 40,
    backgroundColor: '#96bad8',
    borderRadius: 20,
    paddingHorizontal: 12,
    flexDirection: 'row',
    marginTop: 20,
  },
  input: {
    flex: 1,
  },
});
